import { GetUser, postavatar, postname } from "../../api/user";
import { toast } from "../../utils/wxapi";
import { err } from "../../utils/console";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    user: {},
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getuser();
  },
  async getuser() {
    try {
      const res = await GetUser();
      if (res.statusCode === 200) {
        this.setData({ user: res.data });
        wx.setStorageSync("user", res.data);
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  avatar(e: any) {
    console.log(e);
    wx.showLoading({
      title: "上传中",
    });
    try {
      const { avatarUrl } = e.detail;
      const timestamp = new Date().valueOf();
      wx.cloud.uploadFile({
        cloudPath: "head_url/" + timestamp + ".png",
        filePath: avatarUrl,
        success: (res) => {
          const data = { avatar: res.fileID };
          postavatar(data).then((ress: any) => {
            console.log(ress);
            if (ress.statusCode === 200) {
              toast("修改成功");
              this.getuser();
            } else {
              toast("修改失败");
              err(ress.data);
            }
          });
        },
        fail: (error) => {
          err(error);
          toast("上传失败");
        },
      });
    } catch (error) {
      err(error);
      toast("上传失败");
    }
  },
  putname() {
    wx.showModal({
      title: "修改昵称",
      editable: true,
      complete: (res: any) => {
        if (res.confirm) {
          const newUsername = res.content.trim(); // 获取用户输入的新昵称
          if (newUsername === "") {
            toast("昵称不能为空");
            return;
          }
          const data = { username: newUsername };
          postname(data)
            .then((ress: any) => {
              console.log(ress);
              if (ress.statusCode === 200) {
                toast("修改成功");
                this.getuser();
              } else {
                toast("修改失败");
                err(res.data);
              }
            })
            .catch((error: any) => {
              err(error);
            });
        }
      },
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
